using System.Linq;
using SalesPoint.Model;
using Xtensive.Orm;
using Xtensive.Orm.Security;

namespace SalesPoint.Security
{
  public class SalesRepresentativeRole : EmployeeRole
  {
    private static IQueryable<Order> GetOrdersQuery(ImpersonationContext context, QueryEndpoint query)
    {
      // Sales representative role has access to its own orders only
      return query.All<Order>()
        .Where(o => o.Employee == context.Principal);
    }

    private static IQueryable<Customer> GetCustomersQuery(ImpersonationContext context, QueryEndpoint query)
    {
      // Sales representative role has access to local customers only
      var employee = (Employee)context.Principal;
      if (employee.Address.Country.In(Model.WellKnown.NewWorldCountries))
        return query.All<Customer>()
          .Where(c => c.Address.Country.In(Model.WellKnown.NewWorldCountries));
      else
        return query.All<Customer>()
          .Where(c => c.Address.Country.In(Model.WellKnown.OldWorldCountries));
    }

    protected override void RegisterPermissions()
    {
      // Sales representative inherits Employee permissions
      base.RegisterPermissions();

      // Sales representative can see and edit customers
      RegisterPermission(new Permission<Customer>(true, GetCustomersQuery));
      // Sales representative can see and edit sale orders but not approve
      RegisterPermission(new OrderPermission(true, false, GetOrdersQuery));
    }

    public SalesRepresentativeRole(Session session)
      : base(session)
    {
    }
  }
}